<template>
  <div id="chart"></div>
</template>

<script>
  import * as echarts from "echarts";
  import {multiply} from "lodash-es";

  export default {
    name: "Chart",
    props: {
      time: {type: String, default: ''},
      rows: {type: Array, default: () => ([])}
    },
    watch: {
      time() {
        this.createChart()
      }
    },
    methods: {
      createChart() {
        const myChart = echarts.init(document.getElementById('chart'));
        const colors = ['#5470C6', '#91CC75'];
        const option = {
          color: colors,
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            }
          },
          toolbox: {
            feature: {
              saveAsImage: {show: true}
            }
          },
          legend: {
            data: this.rows.map(x => x.name)
          },
          xAxis: [
            {
              type: 'category',
              axisTick: {
                alignWithLabel: true
              },
              data: this.rows.map(x => x.name)
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '人数',
              position: 'left',
              alignTicks: true,
              axisLine: {
                show: true,
                lineStyle: {
                  color: colors[0]
                }
              },
              axisLabel: {
                formatter: '{value}'
              }
            },
            {
              type: 'value',
              name: '占比',
              position: 'right',
              alignTicks: true,
              axisLine: {
                show: true,
                lineStyle: {
                  color: colors[1]
                }
              },
              axisLabel: {
                formatter: '{value} %'
              }
            },
          ],
          series: [
            {
              name: '人数',
              type: 'bar',
              data: this.rows.map(x => x.value)
            },
            {
              name: '占比',
              type: 'line',
              yAxisIndex: 1,
              data: this.rows.map(x => multiply(x.percent, 100).toFixed(2))
            },

          ]
        };
        myChart.setOption(option);
      }
    }
  }
</script>

<style scoped lang="less">
  #chart {
    height: 600px;
    width: 100%;
  }
</style>